package com.learn.egweibo666.base.exception;

import com.learn.egweibo666.base.response.JsonResult;
import com.learn.egweibo666.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandlerException(MethodArgumentNotValidException ex) {
        log.error("参数校验异常：{}", ex.getMessage());
        return JsonResult.ok(StatusCode.VALIDATED_ERROR);
    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintException(ConstraintViolationException ex) {
        log.error("参数校验异常：{}", ex.getMessage());
        return JsonResult.ok(StatusCode.VALIDATED_ERROR);
    }

    @ExceptionHandler
    public JsonResult doHandlerException(RuntimeException ex) {
        log.error("运行时异常：{}", ex.getMessage());
        return JsonResult.ok(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandlerException(Throwable ex) {
        log.error("运行时异常：{}", ex.getMessage());
        return JsonResult.ok(StatusCode.THROWABLE_ERROR);
    }
}
